const mysql = require('mysql2');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'liaoyihu',
    database: 'test'
  });
  connection.connect((err) => {
    if (err) {
      console.error('Error connecting to the database:', err.message);
      return;
    }
    console.log('连接到数据库');
  });
  // 执行查询
 const queryData = async (key, val=0)=>{
  const query = `SELECT * FROM textdata WHERE ${key} = ?`;

    return await new Promise((resolve, reject) => {
        connection.query(query,[val], (err, results, fields) => {
            if (err) {
              console.error('Error executing query:', err.message);
              return;
            }
            console.log('Query results:', results);
          
            resolve(results)
          //   console.log('Query results:', results);
        });
    })
}

// 增加数据
// const insertQuery = 'insert into textdata(name, age) values (?, ?)';
// const insertValues = ['3', '45'];
// connection.query(insertQuery, ['3', '45'], (err, results, fields) => {
//   if (err) {
//     console.error('Error inserting data:', err.message);
//     return;
//   }
//   console.log('Data inserted successfully:', results.insertId);
// });
const addData = async (name, age)=>{
    const insertQuery = 'insert into textdata(name, age) values (?, ?)';
    const insertValues = [name, age];
    return await new Promise((resolve, reject) => {
        connection.query(insertQuery, insertValues, (err, results, fields) => {
            if (err) {
              console.error('Error inserting data:', err.message);
              return;
            }
            console.log('Data inserted successfully:', results.insertId);
            resolve(results.insertId)
          });
    })
}
// const arr = ['kaka ', 'asda', '我靠', '这也行', '牛逼'];
//     arr.forEach((item,index ) => {
//         console.log(index, item)
//         connection.query(insertQuery, [item,index], (err, results, fields) => {
//             if (err) {
//               console.error('Error inserting data:', err.message);
//               return;
//             }
//             console.log('Data inserted successfully:', results.insertId);
//           });
//     })
// 删除数据
// const deleteQuery = 'DELETE FROM textdata WHERE name = ?';

// connection.query(deleteQuery, ['3'], (err, results, fields) => {
//   if (err) {
//     console.error('Error deleting data:', err.message);
//     return;
//   }
//   console.log('Data deleted successfully:', results.affectedRows);
// })
// 修改数据
// const updateQuery = 'UPDATE textdata SET age = ? WHERE name = ?';
// connection.query(updateQuery, ['4', 'aa'], (err, results, fields) => {
//   if (err) {
//     console.error('Error updating data:', err.message);
//     return;
//   }
//   console.log('Data updated successfully:', results.affectedRows);
// })

module.exports = {queryData,addData};